package cn.com.taiji.learn.sshelloworld.config;

import cn.com.taiji.learn.sshelloworld.extend.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity(debug = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .passwordEncoder(passwordEncoder())
//                .withUser("user")
//                .password(passwordEncoder().encode("123456"))
//                .roles("USER")
//                .and().withUser("admin")
//                .password(passwordEncoder().encode("654321"))
//                .roles("ADMIN");

        auth.userDetailsService(customUserDetailsService());
    }

    @Bean
    public CustomUserDetailsService customUserDetailsService(){
        return new CustomUserDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/signup", "/registrationPage", "/user/register").permitAll()
                .antMatchers("/sendEmail","/user/verify/**").permitAll()
                .antMatchers("/user/test/bar").permitAll()
                .antMatchers("/user/test/only-user").hasAnyRole("USER")
                .antMatchers("/user/test/foo").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated();

        http.formLogin().loginPage("/login").permitAll()
                .loginProcessingUrl("/doLogin");
        http.logout().permitAll().logoutUrl("/logout");

        http.csrf().disable();
//        http.headers().frameOptions().disable();
    }

    /**
     * 静态资源开放，避免重定向
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/h2-console/**");
    }
}
